package com.resou.reader.mine.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.assist.WebActivity;
import com.resou.reader.dialog.loading.LoadingDialog;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.utils.log.RsLog;
import com.resou.reader.mine.IView.ILoginView;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.mine.presenter.LoginPresenter;
import com.resou.reader.view.Loading;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class LoginFragment extends DialogFragment implements ILoginView {

    @BindView(R.id.phone_number_edit)
    EditText mPhoneNumbEdit;
    @BindView(R.id.get_verify_code_text)
    TextView mGetVerifyText;
    @BindView(R.id.verify_code_edit)
    EditText mVerifyEdit;
    @BindView(R.id.third_login_layout)
    FrameLayout mThirdLoginLayout;
    @BindView(R.id.phone_login_layout)
    LinearLayout mPhoneLoginLayout;

    @BindView(R.id.third_head_image)
    ImageView mThirdHeadImage;
    @BindView(R.id.third_nickname)
    TextView mThirdNickName;
    @BindView(R.id.btn_login)
    Button mLoginBtn;
    @BindView(R.id.qq_login_btn)
    TextView mQQLoginBtn;

    @BindView(R.id.weixin_login_btn)
    TextView mWeChatLoginBtn;

    @BindView(R.id.login_hint)
    TextView mLoginHint;

    private LoginPresenter mPresenter;
    Unbinder unbinder;
    View contentView;
    String loginType = "2";//默认微信登录
    String unionid = "";
    String gender = "";
    String name = "";
    String openId = "";
    String icon = "";
    String city = "";
    String sex = "";

    @SuppressLint("StaticFieldLeak")
    private static LoginFragment sLoginFragment;
    private LoginListener mLoginListener;
    private LoadingDialog mDialog;

    public LoginFragment() {
    }

    Activity mActivity;

    public static LoginFragment getInstance() {
        if (sLoginFragment == null) {
            synchronized (LoginFragment.class) {
                if (sLoginFragment == null) {
                    sLoginFragment = new LoginFragment();
                }
            }
        }
        return sLoginFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }

    public void setLoginListener(LoginListener loginListener) {
        if (loginListener == null) {
            throw new RuntimeException("必须传递LoginListener给loginFragment");
        }
        this.mLoginListener = loginListener;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new LoginPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        contentView = inflater.inflate(R.layout.fragment_login, container, false);
        unbinder = ButterKnife.bind(this, contentView);
        initView();
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        super.onActivityCreated(savedInstanceState);
        window.setBackgroundDrawableResource(R.drawable.bg_login_fragment);
        WindowManager.LayoutParams attr = window.getAttributes();
        attr.width = WindowManager.LayoutParams.WRAP_CONTENT;
        attr.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(attr);
        window.setWindowAnimations(R.style.LoginFragmentAnimation);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (!isAdded() || isHidden()) {
            mPresenter.onViewDismiss();
        }
    }

    private void clearData() {
        try {
            if (mVerifyEdit != null)
                mVerifyEdit.setText("");
            if (mPhoneNumbEdit != null)
                mPhoneNumbEdit.setText("");
            updateVerifyText(ReSouApplication.getRSApplication().getString(R.string.user_login_get_code), true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (!isAdded())
            super.show(manager, tag);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        mDialog = null;
    }

    private void initView() {
        mPhoneNumbEdit.addTextChangedListener(textWatcher);
        mVerifyEdit.addTextChangedListener(textWatcher);
        setLoginBtnState();
//        mPhoneNumbEdit.setText("18852671330");
        SpannableStringBuilder ssb = new SpannableStringBuilder("登录代表同意用户协议和隐私政策");
        ClickableSpan userProtocolSpan = new ClickableSpan() {//用户协议
            @Override
            public void onClick(@NonNull View widget) {
//                startActivity(new Intent(getActivity(), ScrollingActivity.class));
                WebActivity.startActivity(getActivity(), "https://m.resouxs.com/login/protocol?app=app", "用户协议");

            }
        };

        ClickableSpan privacyPolicySpan = new ClickableSpan() {//隐私政策
            @Override
            public void onClick(@NonNull View widget) {
                WebActivity.startActivity(getActivity(), "https://m.resouxs.com/login/privacy?app=app", "隐私协议");
//                startActivity(new Intent(getActivity(), ScrollingActivity.class).putExtra("privacy_policy", true));
            }
        };

        ssb.setSpan(userProtocolSpan, ssb.length() - 9, ssb.length() - 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(privacyPolicySpan, ssb.length() - 4, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        mLoginHint.setText(ssb);
        mLoginHint.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @OnClick({R.id.btn_login, R.id.qq_login_btn, R.id.weixin_login_btn, R.id.get_verify_code_text})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_verify_code_text:
                mPresenter.sendSMSCode(mPhoneNumbEdit.getText().toString());
                mGetVerifyText.setClickable(false);
                break;
            case R.id.btn_login:
//                mDialog = LoadingDialog.newInstance("登录中...");
//                mDialog.show(getFragmentManager(), "loading_dialog");
                Loading.getInstance().setLoadingText("登录中...");
                Loading.getInstance().show(getFragmentManager());
                mPresenter.mergeAccount(0, mPhoneNumbEdit.getText().toString(), null);
                break;
            case R.id.qq_login_btn:
                boolean isQQInstall = UMShareAPI.get(ReSouApplication.getRSApplication()).isInstall(getActivity(), SHARE_MEDIA.QQ);
                if (!isQQInstall) {
                    Toast.makeText(getActivity(), "QQ未安装", Toast.LENGTH_SHORT).show();
                } else {
//                    mDialog = LoadingDialog.newInstance("授权中...");
//                    mDialog.show(getFragmentManager(), "loading_dialog");
                    Loading.getInstance().setLoadingText("授权中...");
                    Loading.getInstance().show(getFragmentManager());
                    thirdPartyLogin(SHARE_MEDIA.QQ);
                    dismiss();
                }
                break;
            case R.id.weixin_login_btn:
                boolean isWXInstall = UMShareAPI.get(ReSouApplication.getRSApplication()).isInstall(getActivity(), SHARE_MEDIA.WEIXIN);
                if (!isWXInstall) {
                    Toast.makeText(getActivity(), "微信未安装", Toast.LENGTH_SHORT).show();
                } else {
//                    mDialog = LoadingDialog.newInstance("授权中...");
//                    mDialog.show(getFragmentManager(), "loading_dialog");
                    Loading.getInstance().setLoadingText("授权中...");
                    Loading.getInstance().show(getFragmentManager());
                    thirdPartyLogin(SHARE_MEDIA.WEIXIN);
                    dismiss();
                }
                break;
        }
    }

    @Override
    public void toastMsg(String msg) {
        Toast.makeText(ReSouApplication.getRSApplication(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateVerifyText(String text, boolean isFinished) {
        if (!isAdded() || isHidden()) {
            mPresenter.onViewDismiss();
            return;
        }
        mGetVerifyText.setText(text);
        mGetVerifyText.setClickable(isFinished);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        clearData();
        mPresenter.onViewDismiss();
    }

    @Override
    public void hideProgress() {
        if (mDialog != null && mDialog.isAdded()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void phoneLogin() {
        mPresenter.smsLogin(mLoginListener, mPhoneNumbEdit.getText().toString(), mVerifyEdit.getText().toString());
    }

    @Override
    public void winXinLogin(SHARE_MEDIA platform) {
        mPresenter.login(platform, loginType, unionid, sex, name, icon, mLoginListener);
    }

    @Override
    public void qqLogin(SHARE_MEDIA platform) {
        mPresenter.login(platform, loginType, unionid, sex, name, icon, mLoginListener);
    }


    private void setLoginBtnState() {
        boolean clickable = !TextUtils.isEmpty(mPhoneNumbEdit.getText()) && mPhoneNumbEdit.getText().toString().length() == 11 &&
                !TextUtils.isEmpty(mVerifyEdit.getText()) && mVerifyEdit.getText().toString().length() == 6;
        mLoginBtn.setPressed(!clickable);
        mLoginBtn.setClickable(clickable);
        if (!TextUtils.isEmpty(mPhoneNumbEdit.getText()) && mPhoneNumbEdit.getText().toString().length() == 11) {
            mGetVerifyText.setTextColor(getResources().getColor(R.color.btn_login_highlight));
            mGetVerifyText.setClickable(true);
        } else {
            mGetVerifyText.setTextColor(getResources().getColor(R.color.color_gray));
            mGetVerifyText.setClickable(false);
        }
    }

    private static final String TAG = "LoginFragment-App";

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setLoginBtnState();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    private void thirdPartyLogin(SHARE_MEDIA platform) {
        UMShareAPI.get(mActivity).getPlatformInfo(mActivity, platform, authListener);
    }

    /**
     * 微信登录
     * QQ登录
     */

    private UMAuthListener authListener = new UMAuthListener() {

        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Log.d(TAG, "onStart: " + platform.getName());
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(final SHARE_MEDIA platform, int action, Map<String, String> data) {
            Log.d(TAG, "onComplete: ");
            unionid = data.get("unionid");//用户唯一标识
            openId = data.get("openid");
            name = data.get("screen_name");//用户昵称
            gender = data.get("gender");//用户性别
            icon = data.get("profile_image_url");//用户头像
            city = data.get("city");//
            sex = "1";
            loginType = "2";
            if ("女".equalsIgnoreCase(gender)) {
                sex = "2";
            }

            if (platform == SHARE_MEDIA.QQ) {
                loginType = "3";
                Log.d(TAG, "onComplete: " + loginType);
            }

            Loading.getInstance().setLoadingText("登录中...");
            if (loginType.equals("2")) {
                mPresenter.mergeAccount(1, unionid, null);
            } else {
                mPresenter.mergeAccount(2, unionid, null);
            }
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param throwable 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable throwable) {
            ErrorUtils.showError(throwable);
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            if (mDialog != null) {
                mDialog.dismiss();
            }
            Loading.getInstance().dismiss();
        }
    };

    @Override
    public Context getViewContext() {
        return mActivity;
    }

    interface OnLoginInteractionListener {
        void onLoginSuccess();

        void onLoginFailed();

        void onLoginCancel();
    }

}
